package com.zmn.oms.third.toutiao.util;

import org.apache.commons.codec.binary.Hex;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

/**
 * @author: huangyifeng
 * @description: SHA256签名
 * @create: 2019-12-23 11:20
 **/

public class SHAUtil {
    /**
     * sha256_HMAC加密
     * @param message 消息
     * @param secret  秘钥
     * @return 加密后字符串
     */
    public static String sha256_HMAC(String message, String secret) throws Exception{
            Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
            SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes(), "HmacSHA256");
            sha256_HMAC.init(secret_key);
            byte[] bytes = sha256_HMAC.doFinal(message.getBytes());
            String hash = Hex.encodeHexString(bytes);
        return base64(hash);
    }

    public static String base64(String hax){
        return Base64.getEncoder().encodeToString(hax.getBytes());
    }
}
